package com.snap.vseries.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.orhanobut.logger.Logger;
import com.snap.vseries.AppConfig;
import com.snap.vseries.R;
import com.snap.vseries.adapter.NewExperimentTemplateAdapter;
import com.snap.vseries.base.BaseFragment;
import com.snap.vseries.base.OnItemClickListener;
import com.snap.vseries.bean.ExpEntity;
import com.snap.vseries.bean.ExpInfo;
import com.snap.vseries.manager.FileManager;
import com.snap.vseries.model.DBManager;
import com.snap.vseries.threadmanager.ThreadListener;
import com.snap.vseries.threadmanager.ThreadManger;
import com.snap.vseries.ui.ExpNewExperimentActivity;

import org.litepal.crud.callback.UpdateOrDeleteCallback;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;

@SuppressLint("ValidFragment")
public class NewExperimentTemplateFragment extends BaseFragment {
    @BindView(R.id.template_rv)
    RecyclerView templateRecycleView;
    /**
     * 开发者设置模板
     */
    public final static String CUSTOM_SETTING = "Custom Setting";
    private List<ExpEntity> templateList = new ArrayList<>();
    private ExpInfo expInfo;
    private NewExperimentTemplateAdapter adapter;


    @SuppressLint("ValidFragment")
    public NewExperimentTemplateFragment(ExpInfo expInfo) {
        this.expInfo = expInfo;
    }

    @Override
    protected int layoutResId() {
        return R.layout.fragment_new_experiment_template;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setIndex();
        ThreadManger.get().add(new ThreadListener() {
            @Override
            public void doAction() throws Exception {
                refreshTempData();
            }
        });
    }

    private void refreshTempData() {
        List<ExpEntity> list = DBManager.get().getTemplateList();
        if (list.size() != 0) {
            templateList = list;
            Iterator<ExpEntity> iterator = templateList.iterator();
            while (iterator.hasNext()) {
                ExpEntity entity = iterator.next();
                ExpInfo project = FileManager.getInstance().getTempDataByName(entity.getTestProject());
                if (project == null) {
                    Logger.i("模板不存在，想要清除数据库记录" + entity.getTestProject());
                    DBManager.get().deleteTemplate(new UpdateOrDeleteCallback() {
                        @Override
                        public void onFinish(int rowsAffected) {
                            if (rowsAffected > 0) {
                                FileManager.getInstance().removeTempData(entity.getTestProject());
                                Logger.i("清除数据库记录成功");
                            }
                        }
                    }, entity.getTestProject());
                }
            }
        }
        if (AppConfig.Dynamic.custom_setting) {
            templateList.add(new ExpEntity(CUSTOM_SETTING, "Engineer's backdoor"));
        }
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                initViews();
            }
        });
    }


    private void initViews() {
        //====================================测试数据=================================
        templateRecycleView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        adapter = new NewExperimentTemplateAdapter(templateList, getContext(), new OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView.Adapter adapter, View v, int position) {
                expInfo.setTestProject(templateList.get(position).getTestProject());
                ExpNewExperimentActivity activity = (ExpNewExperimentActivity) getActivity();
                Objects.requireNonNull(activity).showFragment(1);
            }
        });
        templateRecycleView.setAdapter(adapter);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            setIndex();
            initData();
        }
    }

    private void initData() {
        expInfo.setProgram(null);
        expInfo.setHoleInfo(null);
        expInfo.setFamName(null);
        expInfo.setVicName(null);
        expInfo.setRoxName(null);
        expInfo.setCy5Name(null);
    }

    private void setIndex() {
        ExpNewExperimentActivity activity = (ExpNewExperimentActivity) getActivity();
        Objects.requireNonNull(activity).index = 0;
    }
}
